package com.cjst.controller.api.location;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.location.ManagedLocation;
import com.cjst.pojo.location.Scenic;
import com.cjst.pojo.part.Parts;
import com.cjst.pojo.sys.SysOffice;
import com.cjst.pojo.sys.SysUser;
import com.cjst.service.location.ManagedLocationService;
import com.cjst.service.location.ScenicService;
import com.cjst.service.part.PartsService;
import com.cjst.service.sys.SysOfficeService;
import com.cjst.service.sys.SysUserService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.BaiduMapUtil;
import com.cjst.util.GpsUtil;
import com.cjst.util.HttpUtil;
import com.cjst.util.UserPrincipalUtil;
import com.cjst.util.common.ResultCode;
import com.cjst.util.json.ResultObj;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/api/location")
public class LocationController extends BaseController {

	private static final Logger log = Logger.getLogger(LocationController.class);
	@Autowired
	private SysOfficeService sysOfficeService;
	@Autowired
	private ManagedLocationService managedLocationService;
	
	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private ScenicService scenicService;

	@Autowired
	private PartsService partsService;

	@RequestMapping(value = "/test", method = RequestMethod.POST)
	@ResponseBody
	public String test() {
		String[] a= {"AKJASD89W3BIUAD781EUI2E9AD",
				"ASDUIQDRW9823HE912E3IKQWED",
				"KJASJDOIWJUAHSDUIWQEDK",
				"KUASHDIUWENUISDHIUADS",
				"OIADH38ERWFDNHIUSF983",
				"SADASFSDFSDSD",
				"SDFSDFEWFEFSVC"};
		Random r=new Random();
		int index=r.nextInt(a.length);
		
		WherePrams wherePrams=Method.where("id", C.EQ, a[index]);
		Scenic tmp=scenicService.get(wherePrams);
		
		return tmp.getName();
	}

	/**
	 * 返回默认的经纬度，用于初始化
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getDefaultLocation", method = RequestMethod.POST)
	@ResponseBody
	public String getDefaultLocation() {
		//WherePrams wheres=Method.where("id", C.EQ, "8TO0SDONRIAR41ZZ7ADB080593AF418694D9B3ABFEDBB1E0");
		/*WherePrams wherePrams = Method.where("id", C.EQ, "SZ41DF5ASD4ZXC54ASD1ZXCF5SDFA");
		ManagedLocation tmp = managedLocationService.get(wherePrams);

		HashMap<String, String> tmpOne = new HashMap<String, String>();
		tmpOne.put("name", tmp.getName());
		tmpOne.put("longitude", tmp.getLongitude());
		tmpOne.put("latitude", tmp.getLatitude());
		tmpOne.put("priority", tmp.getPriority().toString());
		JSONArray result = JSONArray.fromObject(tmpOne);

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("data", result.toString());*/
		SysOffice office=sysOfficeService.get("8TO0SDONRIAR41ZZ7ADB080593AF418694D9B3ABFEDBB1E0");
		HashMap<String, String> tmpOne = new HashMap<String, String>();
		tmpOne.put("name", office.getName());
		tmpOne.put("longitude", office.getLongitude());
		tmpOne.put("latitude", office.getLatitude());
		//tmpOne.put("priority", office.getPriority().toString());
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", tmpOne);
		return robj.toString();
	}

	@RequestMapping(value = "/searchLocation", method = RequestMethod.POST)
	@ResponseBody
	public String searchLocation(@PathVariable String keyword) {
		List<ManagedLocation> tmp = managedLocationService.list(null);
		List<HashMap<String, String>> originResult = new ArrayList<HashMap<String, String>>();

		tmp.forEach(one -> {
			HashMap<String, String> tmpOne = new HashMap<String, String>();
			tmpOne.put("name", one.getName());
			tmpOne.put("longitude", one.getLongitude());
			tmpOne.put("latitude", one.getLatitude());
			tmpOne.put("priority", one.getPriority().toString());
			originResult.add(tmpOne);
		});
		JSONArray result = JSONArray.fromObject(originResult);

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("data", result.toString());

		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", map);
		return robj.toString();
	}

	@RequestMapping(value = "/uploadLocation", method = RequestMethod.POST)
	@ResponseBody
	public String uploadLocation(@PathVariable String location) {
		return null;
	}

	@RequestMapping(value = "/getManagedLocation", method = RequestMethod.POST)
	@ResponseBody
	public String getManagedLocation(String userId) {
//		List<ManagedLocation> tmp = managedLocationService.list(null);
//		List<HashMap<String, String>> originResult = new ArrayList<HashMap<String, String>>();

		
//		WherePrams w=Method.where("id",C.EQ,userId);
//		SysUser sysUser = sysUserService.get(w);
		WherePrams wherePrams=Method.where("type", C.EQ, 0);
		wherePrams.and("status", C.EQ, 1);
		
		/*
		 * 增加权限过滤
		 */
		//UserPrincipalUtil.getPriceMegod(wherePrams, sysUser, null);
		
		
		/*
		tmp.forEach(one -> {
			HashMap<String, String> tmpOne = new HashMap<String, String>();
			tmpOne.put("id", one.getId());
			tmpOne.put("name", one.getName());
			tmpOne.put("longitude", one.getLongitude());
			tmpOne.put("latitude", one.getLatitude());
			tmpOne.put("priority", one.getPriority().toString());
			originResult.add(tmpOne);
		});
		*/
		
		
		
		List<SysOffice> office=sysOfficeService.list(wherePrams);
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", office);
		return robj.toString();
	}

	@RequestMapping(value = "/getScenicLocation", method = RequestMethod.POST)
	@ResponseBody
	public String getScenicLocation(String locationId) {

		WherePrams wherePrams = Method.where("parentId", C.EQ, locationId);
		wherePrams.and("delFlag", C.EQ, "0");
		List<Scenic> tmp = scenicService.list(wherePrams);
		List<HashMap<String, String>> originResult = new ArrayList<HashMap<String, String>>();
		if(tmp!=null) {
			tmp.forEach(one -> {
				HashMap<String, String> tmpOne = new HashMap<String, String>();
				tmpOne.put("id", one.getId());
				tmpOne.put("name", one.getName());
				tmpOne.put("longitude", one.getLongitude());
				tmpOne.put("latitude", one.getLatitude());
				originResult.add(tmpOne);
			});
		}
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", originResult);
		return robj.toString();
	}

	@RequestMapping(value = "/getPartsLocation", method = RequestMethod.POST)
	@ResponseBody
	public String getPartsLocation(String locationId) {
		WherePrams wherePrams = Method.where("areaId", C.EQ, locationId);
		wherePrams.and("delFlag", C.EQ, "0");
		List<Parts> parts = partsService.list(wherePrams);

		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", parts);
		return robj.toString();
	}
	
	
	@RequestMapping(value = "/getPartsDetail", method = RequestMethod.POST)
	@ResponseBody
	public String getPartsDetail(String part_id,Integer type) {					//type为1 获取火星坐标系
		if(type==null){
			type=0;
		}
		WherePrams wherePrams = Method.where("partId", C.EQ, part_id);
		wherePrams.and("delFlag", C.EQ, "0");
		Parts parts = partsService.get(wherePrams);
		if(type==1){
			if(parts.getLonitude()!=null && parts.getLonitude().length()>0 && parts.getLatitude()!=null && parts.getLatitude().length()>0){
				double[] zb=GpsUtil.bd09togcj02(Double.parseDouble(parts.getLonitude()), Double.parseDouble(parts.getLatitude()));
				parts.setLonitude(zb[0]+"");
				parts.setLatitude(zb[1]+"");
				
			}
			
		}
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", parts);
		return robj.toString();
	}

	@RequestMapping(value = "/getSearchByRegion", method = RequestMethod.POST)
	@ResponseBody
	public String getSearchByRegion(String query, String region) {
		String url = BaiduMapUtil.getSearchByRegion(query, region);
		String result = null;
		try {
			result = HttpUtil.httpGET(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	@RequestMapping(value = "/getSearchByRadius", method = RequestMethod.POST)
	@ResponseBody
	public String getSearchByRadius(String query, String location,
			@PathVariable String radius) {
		String url = BaiduMapUtil.getSearchByRadius(query, location, radius);
		String result = null;
		try {
			result = HttpUtil.httpGET(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	@RequestMapping(value = "/getSearchByBounds", method = RequestMethod.POST)
	@ResponseBody
	public String getSearchByBounds(String query, String bounds) {
		String url = BaiduMapUtil.getSearchByBounds(query, bounds);
		String result = null;
		try {
			result = HttpUtil.httpGET(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 
	 * @param uid
	 * @param scope 1 or 2
	 * @return
	 */
	@RequestMapping(value = "/getdetailByUid", method = RequestMethod.POST)
	@ResponseBody
	public String getdetailByUid(String uid, String scope) {
		String url = BaiduMapUtil.getdetailByUid(uid, scope);
		String result = null;
		try {
			result = HttpUtil.httpGET(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 
	 * @param query
	 * @param region
	 * @param city_limit true or false
	 * @return
	 */
	@RequestMapping(value = "/getSuggestion", method = RequestMethod.POST)
	@ResponseBody
	public String getSuggestion(String query, String region,
			@PathVariable String city_limit) {
		// String url=BaiduMapUtil.getSuggestion(query, region,"true");
		String url = BaiduMapUtil.getSuggestion(query, region, city_limit);
		String result = null;
		try {
			result = HttpUtil.httpGET(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * origin=40.01116,116.339303 destination=39.936404,116.452562 纬度在前，经度在后
	 * 
	 * @param origin
	 * @param destination
	 * @return
	 */
	// 步行路线规划
	// http://api.map.baidu.com/directionlite/v1/walking?origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK
	// //GET请求
	@RequestMapping(value = "/getWalkingRoute", method = RequestMethod.POST)
	@ResponseBody
	public String getWalkingRoute(String origin, String destination) {

		String url = BaiduMapUtil.getWalkingRoute(origin, destination);
		String result = null;
		try {
			result = HttpUtil.httpGET(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	// http://api.map.baidu.com/panorama/v2?ak=E4805d16520de693a3fe707cdc962045&width=512&height=256&location=116.313393,40.04778&fov=180
	@RequestMapping(value = "/getPanoView", method = RequestMethod.POST)
	@ResponseBody
	public void getPanoView(int width, int height, String location,
			int fov, HttpServletResponse response) throws IOException {

		String url = BaiduMapUtil.getPanoView(width, height, location, fov);
		byte[] result = null;
		try {
			result = HttpUtil.httpGetImage(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		OutputStream out = response.getOutputStream();
		response.setContentType("image/png");
		out.write(result);
		out.flush();
		out.close();
	}

}
